import React, { useState } from "react";
import InputElement from "../components/InputElement";
import { reg, usernameExist } from "../services/user";
import {useNavigate} from 'react-router-dom';

export default function (props) {
    let [username, setUsername] = useState({ info: "", value: "" });
    let [pwd, setPwd] = useState({ info: "", value: "" });
    let [confirm, setConfirm] = useState({ info: "", value: "" });
    let navigate = useNavigate();
    const validateUsername = async (e) => {
        if (/^\w{6,20}$/.test(e.target.value)) {
            let res = await usernameExist(e.target.value);
            if(res.status == 0){
                setUsername({
                    info: "重名",
                    value: e.target.value,
                });
            }else{
                setUsername({
                    info: "√",
                    value: e.target.value,
                });
            }
            
        } else {
            setUsername({
                info: "x",
                value: e.target.value,
            });
        }
    };
    const validatePwd = (e) => {
        if (/^.{6,20}$/.test(e.target.value)) {
            setPwd({
                info: "√",
                value: e.target.value,
            });
        } else {
            setPwd({
                info: "x",
                value: e.target.value,
            });
        }
    };
    const validateConfirm = (e) => {
        if (e.target.value == pwd.value) {
            setConfirm({
                info: "√",
                value: e.target.value,
            });
        } else {
            setConfirm({
                info: "x",
                value: e.target.value,
            });
        }
    };
    const handleClick = async () => {
        if(username.info == "√"
            && pwd.info == "√"
            && confirm.info == "√"){
                console.log("reg");
            await reg({username:username.value,pwd:pwd.value});
            navigate("/login");

        }

    }
    return (
        <div>
            <h1>注册</h1>
            <InputElement
                type="text"
                validate={validateUsername}
                info={username.info}
            >
                用户名：
            </InputElement>
            <InputElement
                type="password"
                validate={validatePwd}
                info={pwd.info}
            >
                密码：
            </InputElement>
            <InputElement
                type="password"
                validate={validateConfirm}
                info={confirm.info}
            >
                确认密码：
            </InputElement>
            <input type="submit" onClick={handleClick}/>
        </div>
    );
}
